package com.guochenglang.www.controller;


import com.guochenglang.www.pojo.User;
import com.guochenglang.www.service.SearchService;
import com.guochenglang.www.service.SendCode;
import com.guochenglang.www.service.UserService;
import com.guochenglang.www.util.*;
import com.guochenglang.www.web.result.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

/**
 * 密码业务的管理类
 *
 * @author 郭程朗
 */

public class CodeController {
    private static final SendCode SEND_CODE = MyDependency.returnObject(SendCode.class);
    private static final UserService USER_SERVICE = MyDependency.returnObject(UserService.class);

    /**
     * 发送注册验证码
     */
    public static Result sendCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获得用户邮箱
        String email = GetObject.getObject(req, User.class).getEmail();
        //获得验证码
        String code = SEND_CODE.sendCode(email);
        return Result.result(code);
    }

    /**
     * 发送修改密码验证码
     */
    public static Result sendRecoverCode(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        //获得条件
        String email = GetObject.getValue(req, String.class, "email");
        String username = GetObject.getValue(req, String.class, "username");
        User condition = new User();
        condition.setEmail(email);
        condition.setUsername(username);
        ArrayList<User> users = USER_SERVICE.getUser(condition);
        if (users.isEmpty()) {
            return Result.noResult();
        }
        //获得验证码
        String code = SEND_CODE.sendCode(email);
        return Result.result(code);
    }

    /**
     * 生成图片验证码
     */
    public static void imageCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("Content-Disposition", "attachment; filename=code.png");
        resp.setContentType("application/octet-stream");
        //获取随机验证码
        String code = CreateCode.createCode();
        //获得图片
        GetBufferedImage.drawCode(code, resp);
        //验证码存到session中
        req.getSession().setAttribute("code", code);
        //发送图片流
        resp.getOutputStream().flush();
        resp.getOutputStream().close();
    }
}
